﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ledict.ConditionExtract.DAL;
using System.Data;
using Ledict.ConditionExtract.Model;
using Ledict.ConditionExtract.Common;
using System.Xml;
using System.Collections;
using System.IO;


namespace Ledict.ConditionExtract.BLL
{

    public class AnalysisXML
    {

        NewID newid = new NewID();
        CaseCauseDAL casecausedal = new CaseCauseDAL();
        ArgumentTypeXmlDAL argumentTypeXmlDAL = new ArgumentTypeXmlDAL();
        Dictionary<string, string> AllChildDic = new Dictionary<string, string>();
        XmlLabel_SuitTypeRelDAL xmllabel_suittypereldal = new XmlLabel_SuitTypeRelDAL();
        RegexParse.RegexParse getregex = new RegexParse.RegexParse();

        /// <summary>
        /// 解析并添加节点
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="HeadId"></param>
        /// <param name="HeadName"></param>
        public void AnalyAddXMLNode(string XMLText, string HeadId, string HeadName)
        {
            if (!String.IsNullOrEmpty(HeadId))
            {
                XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                XmlDocument document = new XmlDocument();
                document.LoadXml(XMLText);
                XmlNodeList list = document.GetElementsByTagName(HeadName);

                AllChildDic.Clear();
                DataTable AllChildTd = casecausedal.GetAllChild(HeadId);
                for (int i = 0; i < AllChildTd.Rows.Count; i++)
                {
                    AllChildDic.Add(AllChildTd.Rows[i]["CC_ID"].ToString(), AllChildTd.Rows[i]["CC_Name"].ToString());
                }
                if (list.Count > 0)
                {
                    foreach (XmlNode node in list)
                    {
                        xmlProcess(node, HeadId, @"/" + node.Name, HeadId);

                    }

                    casecausedal.CaseCauseUpdateAllPid(HeadId);
                }

                foreach (var item in AllChildDic)
                {
                    casecausedal.UpdateName(item.Key, item.Value);

                }



            }

        }


        public void AnalyArgumentTypeXml(string XMLText, string HeadId)
        {
            XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("、", @"");
            XMLText = getregex.GetParseValue("EI1512151449150001", XMLText);
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLText);
            XmlNodeList list = document.GetElementsByTagName("elementConfig");
            XmlNodeList Childlist = list[0].ChildNodes;
            if (Childlist.Count > 0)
            {
                foreach (XmlNode node in Childlist)
                {
                    ADDOneArgumentType(node, HeadId);

                }

            }
        }






        private void ADDOneArgumentType(XmlNode PNode, string HeadId)
        {
            SYS_ArgumentTypeXml XmlModel = new SYS_ArgumentTypeXml();
            XmlModel.CauseID = HeadId;

            #region  属性

            if (PNode.Attributes.Count > 0)//"属性"节点
            {

                for (int i = 0; i < PNode.Attributes.Count; i++)//下级属性
                {
                    string AttributesName = PNode.Attributes[i].LocalName;
                    string AttributesValue = PNode.Attributes[i].Value;
                    if (AttributesName == "xmlPath")
                    {
                        XmlModel.XmlPath = AttributesValue;
                        break;
                    }
                }
            }
            if (XmlModel.XmlPath != "")
            {
                DataTable dt = casecausedal.GetSYS_CaseCauseByXmlPath(XmlModel.XmlPath);
                if (dt.Rows.Count > 0)
                {
                    XmlModel.ElementID = dt.Rows[0]["CC_ID"].ToString();
                    XmlModel.ElementName = dt.Rows[0]["CC_Name"].ToString();
                }
            }
            #endregion
            string Name = "";
            string Value = "";
            #region 下级节点
            foreach (XmlNode CNode in PNode.ChildNodes)//下级节点 
            {
                Name = CNode.Name;
                Value = CNode.InnerText;

                if (Name == "checkType")
                    XmlModel.Paramter_ISCheck = Value == "check" ? 1 : 0;

                if (Name == "sourceType")
                    XmlModel.SourctType = Value;

                if (Name == "matchKeywords")
                {
                    XmlModel.AT_MatchKeyWord = Value;
                    XmlModel.SourceContent = System.Text.RegularExpressions.Regex.Replace(XmlModel.AT_MatchKeyWord, "[,，].*?(?=(；|;|$))", "");
                }
            }
            #endregion
            if (!String.IsNullOrEmpty(XmlModel.ElementID) && XmlModel.SourctType == "paramter")
            {
                XmlModel.ATX_ID = argumentTypeXmlDAL.Exists(XmlModel);
                if (XmlModel.ATX_ID == "")//没有加
                {
                    XmlModel.ATX_ID = newid.JudgeDoc_CreateID("SYS_ArgumentType_Xml");
                    argumentTypeXmlDAL.Add(XmlModel);
                }
                else //没有改
                {
                    argumentTypeXmlDAL.Update(XmlModel);
                }
            }
        }



        /// <summary>
        /// 处理当前节点的下级
        /// </summary>
        /// <param name="PNode"></param>
        /// <param name="PNodeId"></param>
        private void xmlProcess(XmlNode PNode, string PNodeId, string PXMLRoute, string HeadId)
        {
            #region  属性

            if (PNode.Attributes.Count > 0)//"属性"节点
            {
                string AttributeId = casecausedal.Exists("属性", PNodeId);
                if (!String.IsNullOrEmpty(AttributeId))
                {
                    AllChildDic.Remove(AttributeId);
                }
                else
                {
                    AttributeId = AddNode(AttributeId, "属性", PNodeId, 12, PXMLRoute, 0);
                }

                for (int i = 0; i < PNode.Attributes.Count; i++)//下级属性
                {
                    string AttributesName = PNode.Attributes[i].LocalName;
                    if (!AttributesName.Contains("表述"))
                    {
                        string NotCoreAttributeId = casecausedal.Exists(PNode.Attributes[i].LocalName, AttributeId);//是否存在
                        if (!String.IsNullOrEmpty(NotCoreAttributeId))
                        {
                            AllChildDic.Remove(NotCoreAttributeId);
                            DataTable dt = casecausedal.GetSYS_CaseCauseByCCID(NotCoreAttributeId);
                            NotCoreAttributeId = AddNode(NotCoreAttributeId, AttributesName, AttributeId, 12, PXMLRoute + @"/" + "@" + PNode.Attributes[i].LocalName, Convert.ToInt32(dt.Rows[0]["isLeafNode"]));
                        }
                        else
                        {
                            NotCoreAttributeId = AddNode(NotCoreAttributeId, AttributesName, AttributeId, 12, PXMLRoute + @"/" + "@" + PNode.Attributes[i].LocalName, 0);//添加属性节点 
                        }
                    }
                }
            }
            #endregion

            #region 下级节点
            foreach (XmlNode CNode in PNode.ChildNodes)//下级节点 
            {
                #region 添加节点入库

                string CNodeid = casecausedal.Exists(CNode.Name, PNodeId);
                if (!String.IsNullOrEmpty(CNodeid))//是否存在
                {
                    AllChildDic.Remove(CNodeid);
                    DataTable dt = casecausedal.GetSYS_CaseCauseByCCID(CNodeid);
                    CNodeid = AddNode(CNodeid, CNode.Name, PNodeId, 11, PXMLRoute + @"/" + CNode.Name, Convert.ToInt32(dt.Rows[0]["isLeafNode"]));
                }
                else
                {
                    CNodeid = AddNode(CNodeid, CNode.Name, PNodeId, 11, PXMLRoute + @"/" + CNode.Name, 0);
                }
                //if (!xmllabel_suittypereldal.Exists(CNodeid))
                //{
                //    #region   添加SYS_XmlLabel_SuitTypeRel表

                //    SYS_XmlLabel_SuitTypeRel SuitTypeRelModel = new SYS_XmlLabel_SuitTypeRel();
                //   SuitTypeRelModel.LabelID = CNodeid;
                //   SuitTypeRelModel.XSR_ID = newid.JudgeDoc_CreateID("SYS_XmlLabel_SuitTypeRel");
                //   SuitTypeRelModel.ST_ID = "";

                //   SuitTypeRelModel.LabelXpath = PXMLRoute + @"/" + CNode.Name;
                //   if (SuitTypeRelModel.LabelXpath.Contains("事实要素"))
                //   {
                //       SuitTypeRelModel.LabelType = "Fact";
                //   }
                //   else if (SuitTypeRelModel.LabelXpath.Contains("理由要素"))
                //   {
                //       SuitTypeRelModel.LabelType = "Reason";
                //   }
                //   else
                //   {
                //       SuitTypeRelModel.LabelType = "Suit";
                //   }
                //   xmllabel_suittypereldal.Add(SuitTypeRelModel);
                //    #endregion
                //}

                xmlProcess(CNode, CNodeid, PXMLRoute + @"/" + CNode.Name, HeadId);

                #endregion


            }
            #endregion

        }

        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="NodeName"></param>
        /// <param name="PNodeId"></param>
        /// <returns></returns>
        private string AddNode(string CC_ID, string NodeName, string PNodeId, int NodeType, string XMLRoute, int isLeafNode)
        {
            SYS_CaseCause model = new SYS_CaseCause();

            if (PNodeId != "")
            {

                model.CC_ID = CC_ID == "" ? newid.JudgeDoc_CreateID("SYS_CaseCause") : CC_ID;
                model.CC_Name = NodeName.Trim();
                model.CC_ParentID = PNodeId;// root;
                model.CC_NodeType = NodeType;
                model.isLeafNode = isLeafNode;//叶子1，非叶子0
                model.ElementXML = "";//暂不用
                model.XmlPath = XMLRoute;
                casecausedal.AddSYS_CaseCause(model);

            }
            return model.CC_ID;

        }


        /// <summary>
        /// 更改XML属性
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="XMLPath"></param>
        public string UpdateArgumentTypeXml(string XMLText, string XMLPath, string matchValue)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLText);
            XmlNodeList nodes = document.SelectNodes(string.Format("/elementConfig/element[@xmlPath='{0}']/matchKeywords", XMLPath));
            if (0 < nodes.Count)
            {
                nodes[0].InnerText = matchValue;
            }

            return FormatXml(document.InnerXml);
        }

        /// <summary>
        /// xml格式化
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private string FormatXml(string source)
        {
            StringBuilder sb = new StringBuilder();
            XmlTextWriter writer = null;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(source);

                writer = new XmlTextWriter(new StringWriter(sb));
                writer.Formatting = Formatting.Indented;

                doc.WriteTo(writer);
            }
            finally
            {
                if (writer != null) writer.Close();
            }

            return sb.ToString();
        }

    }
}
